package com.alit.face.koala.service.subject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alit.face.koala.app.data.AppResponse;
import com.alit.face.koala.app.data.EmployeeConstantsData;
import com.alit.face.koala.app.data.EmployeeDetail;
import com.alit.face.koala.app.data.KoalaEmpLoyeeRequest;
import com.alit.face.koala.app.data.Lv;
import com.alit.face.koala.app.data.Page;
import com.alit.face.koala.app.data.PhotoData;
import com.alit.face.koala.entity.KoalaEmpLoyeeEntity;
import com.alit.face.koala.entity.UploadFileEntity;
import com.alit.face.koala.projectvariable.PVK;
import com.alit.face.koala.repository.KoalaEmployeeRepository;
import com.alit.face.koala.service.face.baidu.BaiduFaceService;
import com.alit.face.koala.service.upload.UploadService;
import com.alit.face.koala.util.JsonUtil;
import com.litong.utils.projectvariable.PVU;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SubjectService {

  @Autowired
  private GroupService gruopService;
  @Autowired
  private UploadService uploadService;
  @Autowired
  private KoalaEmployeeRepository koalaEmployeeRepository;
  @Autowired
  private BaiduFaceService baiduFaceService;
  @Autowired
  private BaiduFaceDetecteService baiduFaceDetecteService;

  public AppResponse constants(String category) {
    EmployeeConstantsData data = new EmployeeConstantsData();
    data.setCategory(category);
    List<Lv> department = new ArrayList<>();
    department.add(new Lv("软件开发部", "软件开发部"));
    data.setDepartment(department);

    List<Lv> gender = new ArrayList<>();
    gender.add(new Lv("未选择", 0));
    gender.add(new Lv("男", 1));
    gender.add(new Lv("女", 2));
    data.setGender(gender);

    data.setImport_employee_excel("/static/excel/导入模板-员工.xlsx");
    data.setImport_visitor_excel("/static/excel/导入模板-访客.xlsx");

    data.setSubject_type(0);
    List<Lv> subject_type_options = new ArrayList<>();
    subject_type_options.add(new Lv("员工", 0));
    subject_type_options.add(new Lv("访客", 1));
    subject_type_options.add(new Lv("VIP", 2));
    subject_type_options.add(new Lv("黄名单", 3));
    data.setSubject_type_options(subject_type_options);

    AppResponse response = new AppResponse();
    response.setCode(0);
    response.setData(data);
    response.setPage(new Page());
    return response;
  }

  public AppResponse list(String category) {
    AppResponse resonse = new AppResponse();
    JSONArray data = new JSONArray();
    List<KoalaEmpLoyeeEntity> findAll = koalaEmployeeRepository.findAll();
    for (KoalaEmpLoyeeEntity entity : findAll) {
      EmployeeDetail userDetail = parseKoalEmployeeToEmployeeDetail(entity);
      data.add(userDetail);
    }

    resonse.setCode(0);
    resonse.setData(data);
    resonse.setPage(new Page());
    return resonse;
  }

  public EmployeeDetail parseKoalEmployeeToEmployeeDetail(KoalaEmpLoyeeEntity entity) {
    String fullUri = uploadService.getFullUri(entity.getAvatar());
    entity.setAvatar(fullUri);
    EmployeeDetail userDetail = new EmployeeDetail(entity);
    List<String> photoIds = JSON.parseArray(entity.getPhotoIds(), String.class);
    List<PhotoData> photos = new ArrayList<>();
    for (String id : photoIds) {
      PhotoData photoData = new PhotoData();
      photoData.setCompanyId(1);
      photoData.setSubjectId(entity.getId());
      photoData.setId(id);
      String fullUrl = uploadService.getFullUriById(id);
      // 即使url是正确的,但是页面上不会显
      photoData.setUrl(fullUrl);
      // 界面上读取的是setOriginUrl
      photoData.setOriginUrl(fullUrl);
      photos.add(photoData);
    }
    userDetail.setPhotos(photos);
    return userDetail;
  }

  public AppResponse groupList(int subject_type, int size, int page) {
    return gruopService.groupList(subject_type, size, page);
  }

  /**
   * 保存并显示头像文件 
   */
  public AppResponse avatar(MultipartFile avatar) {
    UploadFileEntity upload = uploadService.upload(avatar);

    JSONObject data = new JSONObject(2);

    // 前台js不读取任何一个,添加用户时使用url
    data.put("image_uri", upload.getUri());
    data.put("url", upload.getUri());

    AppResponse retval = new AppResponse();
    retval.setCode(0);
    retval.setData(data);
    return retval;
  }

  /**
   * 上传人脸照片 
   * 1.上传照片到fdfs
   * 2.判断照片中是否有人脸和其他错误信息,如果有返回错误信息
   * 3.如果没有错误信息,判断照片对应的人脸已经添加了人脸库中,如果已经添加到人脸库中,返回用户id
   */
  public AppResponse photo(MultipartFile photo) {
    // 文件名
    String originalFileName = photo.getOriginalFilename();
    // 拓展名
    String extension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);

    byte[] bytes = null;
    try {
      bytes = photo.getBytes();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return upload(bytes, extension);
  }

  public AppResponse upload(byte[] bytes, String extension) {
    AppResponse retval = new AppResponse();
    UploadFileEntity upload = uploadService.uploadImageFace(bytes, extension);
    org.json.JSONObject detectedResult = baiduFaceDetecteService.detected(upload);
    // 判断人脸检测数据中的错误信息
    int errorCode = JsonUtil.getInt(detectedResult, "error_code");

    org.json.JSONObject jsonResult = null;
    if (errorCode != 0) {
      String errorMsg = JsonUtil.getString(detectedResult, "error_msg");
      retval.setCode(errorCode);
      retval.setDesc(errorMsg);
      return retval;
    } else {
      int faceNum = JsonUtil.getInt(jsonResult, "face_num");
      if (faceNum != 1) {
        retval.setCode(-1);
        retval.setDesc("图片中包含多张人脸");
        return retval;
      }
    }

    // 进行人脸搜索,判断用户是否存在
    // 获取face
    org.json.JSONArray faceList = JsonUtil.getJSONArray(jsonResult, "face_list");
    org.json.JSONObject face = JsonUtil.getJSONObject(faceList, 0);
    // 获取token
    String faceToken = JsonUtil.getString(face, "face_token");

    log.info("face_token:" + faceToken);
    String imageType = "FACE_TOKEN";
    String groups = PVU.getValue(PVK.baiduFaceGroups);
    org.json.JSONObject searchResult = baiduFaceService.search(faceToken, imageType, groups);
    log.info("人脸搜索结果:" + searchResult.toString());
    errorCode = JsonUtil.getInt(searchResult, "error_code");
    String subjectId = null;
    if (errorCode == 0) {
      org.json.JSONObject result = JsonUtil.getJSONObject(searchResult, "result");
      org.json.JSONArray userList = JsonUtil.getJSONArray(result, "user_list");
      org.json.JSONObject jsonObject = JsonUtil.getJSONObject(userList, 0);
      subjectId = JsonUtil.getString(jsonObject, "user_id");
      String userInfo = JsonUtil.getString(jsonObject, "user_info");
      log.info("搜索到人脸subjectId:" + subjectId);
      retval.setCode(-1);
      retval.setDesc("用户已经存在,用户Id和姓名:" + subjectId + "," + userInfo);
      return retval;
    } else {
      log.info("人脸不存在,可以添加:" + upload.getMd5());
    }

    PhotoData data = new PhotoData();
    data.setId(upload.getMd5());
    data.setUrl(upload.getFullUri());
    // 前端读取的是url
    data.setOriginUrl(upload.getUri());
    data.setVersion(7);
    data.setSubjectId(subjectId);
    retval.setCode(0);
    retval.setData(data);
    return retval;
  }

  public AppResponse add(KoalaEmpLoyeeRequest employee) {
    if (PVU.isDev()) {
      log.info("添加用户:" + employee);
      // /upload/xxx.jps 决定对路径开头
      log.info("用户头像:" + employee.getAvatar());
    }
    KoalaEmpLoyeeEntity entity = new KoalaEmpLoyeeEntity(null, employee);
    String value = PVU.getValue(PVK.baiduFaceFamiliarGroupId);
    entity.setBaiduGroupId(value);
    // 保存用户到数据库
    koalaEmployeeRepository.save(entity);
    log.info("添加用户到本地数据库成功,userid:" + entity.getId());
    baiduFaceService.addUser(employee, entity);
    AppResponse retval = new AppResponse();
    retval.setCode(0);
    return retval;
  }

  public AppResponse edit(String id, KoalaEmpLoyeeRequest employee) {
    log.info("修改用户id:" + id);
    if (PVU.isDev()) {
      // 用户头像数据:http://192.168.99.214/store_path/data/00/00/wKhj1l2LVUyAPUgrAD6ymbNYEu405.blob
      log.info("获取到的用户信息:" + JSON.toJSONString(employee));
    }
    KoalaEmpLoyeeEntity entity = new KoalaEmpLoyeeEntity(id, employee);
    entity.setBaiduGroupId(koalaEmployeeRepository.getBaiduGroupId(id));

    // TO DO 编辑时头像
    // 保存用户到数据库
    koalaEmployeeRepository.save(entity);

    // 保存用户到远程库-->baidu
    baiduFaceService.update(employee, entity);
    AppResponse retval = new AppResponse();
    retval.setCode(0);
    return retval;
  }

  public AppResponse delete(String id) {
    // 查询groupId
    String baiduGroupId = koalaEmployeeRepository.getBaiduGroupId(id);
    // 删除远程用户
    org.json.JSONObject deleteById = baiduFaceService.deleteById(id, baiduGroupId);
    log.info("删除远程用户返回:" + deleteById);
    // 删除本地用户
    koalaEmployeeRepository.deleteById(id);

    AppResponse retval = new AppResponse();
    retval.setCode(0);
    retval.setPage(new Page());
    return retval;
  }

  public AppResponse get(String id) {
    AppResponse retval = new AppResponse();
    log.info("查询用户,用户Id:" + id);
    Optional<KoalaEmpLoyeeEntity> findById = koalaEmployeeRepository.findById(id);
    if (findById.isPresent()) {
      EmployeeDetail data = parseKoalEmployeeToEmployeeDetail(findById.get());
      retval.setData(data);
    }
    retval.setCode(0);
    return retval;
  }
}
